/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <stdio.h>
#include <squirrel.h>
#include <sqstdaux.h>
#include "Xern/Entity.hpp"

#include "EntityFactory.hpp"


extern boost::shared_ptr<Xern::Entity> XS_ExtractEntity(HSQUIRRELVM vm, int idx);

namespace XernSquirrel
{
	EntityFactory::EntityFactory(HSQUIRRELVM vm)
		: vm(vm)
	{
	}

	EntityFactory::~EntityFactory()
	{
		// Release the classes by name.
		ClassesByName::iterator nit = classesByName.begin();
		for(; nit != classesByName.end(); nit++)
		{
			HSQOBJECT obj = nit->second;
			sq_release(vm, &obj);
		}

		// Release the classes by guid.
		ClassesByGuid::iterator git = classesByGuid.begin();
		for(; git != classesByGuid.end(); git++)
		{
			HSQOBJECT obj = git->second;
			sq_release(vm, &obj);
		}
	}

	boost::shared_ptr<Entity>
	EntityFactory::CreateEntity(const std::string &classname)
	{
		boost::shared_ptr<Entity> ret;

		// Find the entity class.
		ClassesByName::iterator it = classesByName.find(classname);
		if(it != classesByName.end())
		{
			HSQOBJECT clazz = it->second;

			// Push the class.
			sq_pushobject(vm, clazz);

			// Create a new instance.
			sq_createinstance(vm, -1);

			// Remove the class.
			sq_remove(vm, -2);

			// Find the constructor.
			sq_pushstring(vm, _SC("constructor"), -1);
			if(SQ_SUCCEEDED(sq_get(vm, -2)))
			{
				// push the instance.
				sq_push(vm, -2);

				// Call the constructor.
				if(SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue)))
				{
					// Pop the constructor.
					sq_pop(vm, 1);

					// Extract the entity pointer.
					ret = XS_ExtractEntity(vm, -1);

					// Pop the instance.
					sq_pop(vm, 1);
				}
			}
			else
			{
				sq_pop(vm, 1);
			}
		}

		// Set the class name.
		if(ret)
			ret->SetClassName(classname);

		return ret;
	}

	boost::shared_ptr<Entity>
	EntityFactory::CreateEntity(const uuid &classId)
	{
		boost::shared_ptr<Entity> ret;

		// Find the entity class.
		ClassesByGuid::iterator it = classesByGuid.find(classId);
		if(it != classesByGuid.end())
		{
			HSQOBJECT clazz = it->second;

			// Push the class.
			sq_pushobject(vm, clazz);

			// Create a new instance.
			sq_createinstance(vm, -1);

			// Remove the class.
			sq_remove(vm, -2);

			// Find the constructor.
			sq_pushstring(vm, _SC("constructor"), -1);
			if(SQ_SUCCEEDED(sq_get(vm, -2)))
			{
				// push the instance.
				sq_push(vm, -2);

				// Call the constructor.
				if(SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue)))
				{
					// Pop the constructor.
					sq_pop(vm, 1);

					// Extract the entity pointer.
					ret = XS_ExtractEntity(vm, -1);

					// Pop the instance.
					sq_pop(vm, 1);
				}
			}
		}

		if(ret)
		{
			// Find the class name
			ClassNamesByGuid::iterator cit = classNamesByGuid.find(classId);
			if(cit != classNamesByGuid.end())
			{
				// Set the class name.
				ret->SetClassName(cit->second);
			}
		}

		return ret;
	}

	void EntityFactory::RegisterClass(HSQOBJECT clazz, const std::string &className, uuid guid)
	{
		// Register the class name.
		if(!className.empty())
		{
			sq_addref(vm, &clazz);
			classesByName.insert(std::make_pair(className, clazz));
		}

		// Register the class id.
		if(!guid.is_nil())
		{
			sq_addref(vm, &clazz);
			classesByGuid.insert(std::make_pair(guid, clazz));

			if(!className.empty())
			{
				classNamesByGuid.insert(std::make_pair(guid, className));
			}
		}
	}
};
